$(function() {
    var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
    var textSocket = new WS("@routes.Application.textWs().webSocketURL(request)")

    // Handle the websocket incoming message: update the textarea object
    var receiveEvent = function(event) {
        $("#text").val(event.data);
    }
    textSocket.onmessage = receiveEvent;
    
    // Send out the text content to server upon change
    var sendEvent = function() {
    	textSocket.send($("#text").val());
    }
    $('#text').keyup(sendEvent);
    
    // Save file
    save = function(){ // TODO validation for filename
    	var fname = $.trim($('#filename').val());
    	if (fname == null || fname == "") {
    		alert("You should give a proper file name! " + fname);
    		return false;
    	}
    	var filename = $('#filename').val();
    	$.ajax({url:"/save/" + filename});
    }
    $('#save').click(save);

    // Open file
    var open = function() {
    	var url = '/open';
    	$('#files').html('');
    	$.getJSON(url, function (data) {
    		$.each(data, function(index, value) {
    			//htmlString += value;
    			$.each(value, function(k, v) {
    				$('#files').append(' [<a href="/load/' + v + '">' + v + '</a>] ');
    			});
    		});
    	});
    }
    $('#open').click(open);

})